package com.winit.page.service;

import com.winit.common.base.bean.ExecuteResult;
import com.winit.common.util.ListUtil;
import com.winit.feature.manager.PathContainer;
import com.winit.page.manager.PageManager;
import com.winit.page.model.Page;
import com.winit.page.repository.PageOperations;
import com.winit.page.repository.PageRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class PageServiceImpl implements IPageService {

    private static Logger logger = LoggerFactory.getLogger(PageServiceImpl.class);

    @Autowired
    private PageRepository pageRepository;
    @Autowired
    private PageOperations pageOperations;

    @Autowired
    private PageManager pageManager;
    @Autowired
    private PathContainer pathContainer;
    @Override
    public List<Page> getPagesForMenuId(String menuId, boolean setPath) {
        Object objects =  this.pageManager.getMenuPages(menuId, setPath).getData();
        if (null == objects){
            return null;
        }
        return (List<Page>)objects;
    }

    @Override
    public ExecuteResult deleteAllMenuPage(String menuId, boolean deleteAllPageFeature) {
        ExecuteResult executeResult = new ExecuteResult();
        List<Page> pages = this.pageRepository.findByRefMenuId(menuId);
        if (CollectionUtils.isEmpty(pages)){
            return executeResult;
        }
        for(Page page : pages){
            executeResult = this.pageManager.deletePage(page.getId(), deleteAllPageFeature);
            if (!executeResult.isSuccess()){
                return executeResult;
            }
        }
        return executeResult;
    }
    @Override
    public void updatePageChild(String pageId, String featureId,String type) {
        Page page = pageRepository.findById(pageId);
        if("remove".equals(type)){
            page.setChildren(ListUtil.removeChild(page.getChildren(), featureId));
        }else if("add".equals(type)){
            page.setChildren(ListUtil.addChild(page.getChildren(), featureId));
        }else {
            logger.info("com.winit.page.service.PageServiceImpl.updatePageChild type = "+type);
            return;
        }

        pageOperations.updatePropertiesNotNullById(page);
        pathContainer.updatePath(pageId, page.getMenuId(), page.getTitle(), page.getChildren());
    }
}
